from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify, session
from flask_login import login_user, logout_user, login_required, current_user
from extensions import db
from models import User, Coach, Course, Booking, Activity, Post
from forms import LoginForm, RegisterForm, BookingForm, ContactForm
from datetime import datetime, timedelta
from functools import wraps
from sqlalchemy import func, or_
from werkzeug.urls import url_parse
from werkzeug.utils import secure_filename
import os
import time
from config import Config  # 导入配置

# 创建蓝图
main_bp = Blueprint('main', __name__)

# 管理员权限装饰器
def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_admin:
            flash('您没有权限访问此页面', 'danger')
            return redirect(url_for('main.index'))
        return f(*args, **kwargs)
    return decorated_function

def get_default_image(type):
    """提供默认图片 URL"""
    defaults = {
        'course': url_for('static', filename='img/default-course.jpg'),
        'coach': url_for('static', filename='img/default-coach.jpg'),
        'activity': url_for('static', filename='img/default-activity.jpg')
    }
    return defaults.get(type, defaults['course'])

@main_bp.route('/')
def index():
    activities = Activity.query.order_by(Activity.date.desc()).limit(3).all()
    coaches = Coach.query.limit(4).all()
    courses = Course.query.all()
    return render_template('index.html', 
                          activities=activities, 
                          coaches=coaches, 
                          courses=courses,
                          get_default_image=get_default_image)

# 关于我们
@main_bp.route('/about')
def about():
    return render_template('about.html')

# 课程列表
@main_bp.route('/courses')
def courses():
    courses = Course.query.all()
    return render_template('courses.html', courses=courses)

# 课程详情
@main_bp.route('/course/<int:id>')
def course_detail(id):
    course = Course.query.get_or_404(id)
    return render_template('course_detail.html', course=course)

# 教练团队
@main_bp.route('/coaches')
def coaches():
    coaches = Coach.query.all()
    return render_template('coaches.html', coaches=coaches)

# 教练详情
@main_bp.route('/coach/<int:id>')
def coach_detail(id):
    coach = Coach.query.get_or_404(id)
    return render_template('coach_detail.html', coach=coach)

# 历史活动
@main_bp.route('/activities')
def activities():
    activities = Activity.query.order_by(Activity.date.desc()).all()
    return render_template('activities.html', activities=activities)

# 活动详情
@main_bp.route('/activity/<int:id>')
def activity_detail(id):
    activity = Activity.query.get_or_404(id)
    return render_template('activity_detail.html', activity=activity)

# 潜水知识
@main_bp.route('/knowledge')
def knowledge():
    # 查询潜水知识文章
    posts = Post.query.filter_by(category="潜水知识").order_by(Post.created_at.desc()).all()
    return render_template('knowledge.html', posts=posts)
def post_detail(id):
    post = Post.query.get_or_404(id)
    return render_template('post_detail.html', post=post)

# 用户注册
@main_bp.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data, phone=form.phone.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('注册成功，请登录！')
        return redirect(url_for('main.login'))
    return render_template('register.html', form=form)

# 用户登录
@main_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        if current_user.is_admin:
            return redirect(url_for('main.admin_dashboard'))
        return redirect(url_for('main.index'))
    
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('邮箱或密码错误', 'danger')
            return redirect(url_for('main.login'))
        
        login_user(user, remember=form.remember_me.data)
        
        if user.is_admin:
            return redirect(url_for('main.admin_dashboard'))
        
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('main.index')
        return redirect(next_page)
    
    return render_template('login.html', title='登录', form=form)

# 用户登出
@main_bp.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('main.index'))

# 用户个人中心
@main_bp.route('/profile')
@login_required
def profile():
    bookings = Booking.query.filter_by(user_id=current_user.id).order_by(Booking.booking_date.desc()).all()
    return render_template('profile.html', bookings=bookings)

# 预约潜水
@main_bp.route('/booking', defaults={'course_id': None})
@main_bp.route('/booking/<int:course_id>')
@login_required
def booking(course_id):
    """预约课程"""
    form = BookingForm()
    
    # 设置课程选项
    form.course.choices = [(c.id, f"{c.name} - ¥{c.price}") for c in Course.query.all()]
    
    # 如果提供了课程ID，预先选择该课程
    if course_id:
        form.course.data = course_id
    
    form.coach.choices = [(c.id, c.name) for c in Coach.query.filter_by(availability=True).all()]
    
    if form.validate_on_submit():
        # 获取选择的课程
        selected_course = Course.query.get(form.course.data)
        
        booking = Booking(
            user_id=current_user.id,
            coach_id=form.coach.data,
            course_id=form.course.data,
            booking_date=form.date.data,
            participants=form.participants.data,
            is_group=form.is_group.data,
            total_price=selected_course.price * form.participants.data
        )
        db.session.add(booking)
        db.session.commit()
        
        flash('预约成功，请等待确认！')
        return redirect(url_for('main.payment', booking_id=booking.id))
    
    return render_template('booking.html', form=form)

# 支付页面
@main_bp.route('/payment/<int:booking_id>')
@login_required
def payment(booking_id):
    booking = Booking.query.get_or_404(booking_id)
    if booking.user_id != current_user.id:
        flash('无权访问此页面')
        return redirect(url_for('main.index'))
    return render_template('payment.html', booking=booking)

# 处理支付
@main_bp.route('/process_payment/<int:booking_id>', methods=['POST'])
@login_required
def process_payment(booking_id):
    booking = Booking.query.get_or_404(booking_id)
    if booking.user_id != current_user.id:
        return jsonify({'success': False, 'message': '无权操作'})
    
    # 这里应该有实际的支付处理逻辑
    # 假设支付成功
    booking.payment_status = 'paid'
    booking.status = 'confirmed'
    db.session.commit()
    
    return jsonify({'success': True, 'message': '支付成功'})

# 拼团页面
@main_bp.route('/group_booking')
def group_booking():
    group_bookings = Booking.query.filter_by(is_group=True, status='pending').all()
    return render_template('group_booking.html', bookings=group_bookings)

# 加入拼团
@main_bp.route('/join_group/<int:booking_id>', methods=['GET', 'POST'])
@login_required
def join_group(booking_id):
    original_booking = Booking.query.get_or_404(booking_id)
    if request.method == 'POST':
        participants = int(request.form.get('participants', 1))
        new_booking = Booking(
            user_id=current_user.id,
            coach_id=original_booking.coach_id,
            course_id=original_booking.course_id,
            booking_date=original_booking.booking_date,
            participants=participants,
            is_group=True,
            total_price=original_booking.course.price * participants
        )
        db.session.add(new_booking)
        db.session.commit()
        flash('成功加入拼团！')
        return redirect(url_for('payment', booking_id=new_booking.id))
    
    return render_template('join_group.html', booking=original_booking)

# 联系我们
@main_bp.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        # 处理联系表单提交
        flash('消息已发送，我们会尽快回复您！')
        return redirect(url_for('contact'))
    return render_template('contact.html', form=form)

# 管理后台首页
@main_bp.route('/admin')
@login_required
@admin_required
def admin_dashboard():
    # 统计数据
    stats = {
        'users_count': User.query.count(),
        'bookings_count': Booking.query.count(),
        'courses_count': Course.query.count(),
        'activities_count': Activity.query.count()
    }
    
    # 最近预约
    recent_bookings = Booking.query.order_by(Booking.created_at.desc()).limit(5).all()
    
    # 最新用户
    recent_users = User.query.order_by(User.created_at.desc()).limit(5).all()
    
    # 预约统计数据（最近7天）
    booking_stats = {'labels': [], 'data': []}
    for i in range(6, -1, -1):
        date = datetime.now() - timedelta(days=i)
        date_str = date.strftime('%m-%d')
        booking_stats['labels'].append(date_str)
        count = Booking.query.filter(
            func.date(Booking.created_at) == func.date(date)
        ).count()
        booking_stats['data'].append(count)
    
    # 课程分布统计
    course_stats = {'labels': [], 'data': []}
    courses = Course.query.all()
    for course in courses:
        course_stats['labels'].append(course.name)
        count = Booking.query.filter_by(course_id=course.id).count()
        course_stats['data'].append(count)
    
    return render_template('admin/dashboard.html', 
                           stats=stats, 
                           recent_bookings=recent_bookings,
                           recent_users=recent_users,
                           booking_stats=booking_stats,
                           course_stats=course_stats)

# 用户管理
@main_bp.route('/admin/users')
@login_required
@admin_required
def admin_users():
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    filter_type = request.args.get('filter', 'all')
    
    query = User.query
    
    # 搜索
    if search:
        query = query.filter(
            or_(
                User.username.like(f'%{search}%'),
                User.email.like(f'%{search}%')
            )
        )
    
    # 过滤
    if filter_type == 'admin':
        query = query.filter_by(is_admin=True)
    elif filter_type == 'member':
        query = query.filter_by(is_member=True)
    elif filter_type == 'regular':
        query = query.filter_by(is_admin=False, is_member=False)
    
    # 分页
    pagination = query.order_by(User.id.desc()).paginate(
        page=page, per_page=10, error_out=False
    )
    users = pagination.items
    
    return render_template('admin/users.html', users=users, pagination=pagination)

# 添加用户
@main_bp.route('/admin/users/add', methods=['POST'])
@login_required
@admin_required
def admin_add_user():
    username = request.form.get('username')
    email = request.form.get('email')
    phone = request.form.get('phone')
    password = request.form.get('password')
    is_admin = 'is_admin' in request.form
    is_member = 'is_member' in request.form
    
    # 检查用户名和邮箱是否已存在
    if User.query.filter_by(username=username).first():
        flash('用户名已存在', 'danger')
        return redirect(url_for('admin_users'))
    
    if User.query.filter_by(email=email).first():
        flash('邮箱已存在', 'danger')
        return redirect(url_for('admin_users'))
    
    # 创建新用户
    user = User(
        username=username,
        email=email,
        phone=phone,
        is_admin=is_admin,
        is_member=is_member,
        created_at=datetime.utcnow()
    )
    
    if is_member:
        user.member_since = datetime.utcnow()
    
    user.set_password(password)
    db.session.add(user)
    db.session.commit()
    
    flash('用户添加成功', 'success')
    return redirect(url_for('admin_users'))

# 编辑用户
@main_bp.route('/admin/users/<int:id>/edit', methods=['POST'])
@login_required
@admin_required
def admin_edit_user(id):
    user = User.query.get_or_404(id)
    
    username = request.form.get('username')
    email = request.form.get('email')
    phone = request.form.get('phone')
    password = request.form.get('password')
    is_admin = 'is_admin' in request.form
    is_member = 'is_member' in request.form
    
    # 检查用户名和邮箱是否已被其他用户使用
    username_exists = User.query.filter(User.username == username, User.id != id).first()
    if username_exists:
        flash('用户名已存在', 'danger')
        return redirect(url_for('admin_users'))
    
    email_exists = User.query.filter(User.email == email, User.id != id).first()
    if email_exists:
        flash('邮箱已存在', 'danger')
        return redirect(url_for('admin_users'))
    
    # 更新用户信息
    user.username = username
    user.email = email
    user.phone = phone
    user.is_admin = is_admin
    
    # 处理会员状态变更
    if is_member and not user.is_member:
        user.is_member = True
        user.member_since = datetime.utcnow()
    elif not is_member and user.is_member:
        user.is_member = False
        user.member_since = None
    
    # 如果提供了新密码，则更新密码
    if password:
        user.set_password(password)
    
    db.session.commit()
    
    flash('用户信息更新成功', 'success')
    return redirect(url_for('admin_users'))

# 删除用户
@main_bp.route('/admin/users/<int:id>/delete')
@login_required
@admin_required
def admin_delete_user(id):
    user = User.query.get_or_404(id)
    
    # 不允许删除自己
    if user.id == current_user.id:
        flash('不能删除当前登录的管理员账户', 'danger')
        return redirect(url_for('admin_users'))
    
    db.session.delete(user)
    db.session.commit()
    
    flash('用户删除成功', 'success')
    return redirect(url_for('admin_users'))

# 教练管理
@main_bp.route('/admin/coaches')
@login_required
@admin_required
def admin_coaches():
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    filter_type = request.args.get('filter', 'all')
    
    query = Coach.query
    
    # 搜索
    if search:
        query = query.filter(Coach.name.like(f'%{search}%'))
    
    # 过滤
    if filter_type == 'available':
        query = query.filter_by(availability=True)
    elif filter_type == 'unavailable':
        query = query.filter_by(availability=False)
    
    pagination = query.order_by(Coach.id.desc()).paginate(page=page, per_page=10, error_out=False)
    coaches = pagination.items
    
    return render_template('admin/coaches.html', coaches=coaches, pagination=pagination)

# 添加教练
@main_bp.route('/admin/coaches/add', methods=['POST'])
@login_required
@admin_required
def admin_add_coach():
    name = request.form.get('name')
    specialty = request.form.get('specialty')
    experience = request.form.get('experience', type=int)
    availability = 'availability' in request.form
    introduction = request.form.get('introduction')
    
    # 处理照片上传
    photo = request.files.get('photo')
    if photo and allowed_file(photo.filename):
        filename = secure_filename(f"coach_{int(time.time())}_{photo.filename}")
        photo.save(os.path.join(Config.UPLOAD_FOLDER, filename))
    else:
        flash('请上传有效的图片文件', 'danger')
        return redirect(url_for('admin_coaches'))
    
    coach = Coach(
        name=name,
        specialty=specialty,
        experience=experience,
        availability=availability,
        introduction=introduction,
        photo=filename
    )
    
    db.session.add(coach)
    db.session.commit()
    
    flash('教练添加成功', 'success')
    return redirect(url_for('admin_coaches'))

# 编辑教练
@main_bp.route('/admin/coaches/<int:id>/edit', methods=['POST'])
@login_required
@admin_required
def admin_edit_coach(id):
    coach = Coach.query.get_or_404(id)
    
    coach.name = request.form.get('name')
    coach.specialty = request.form.get('specialty')
    coach.experience = request.form.get('experience', type=int)
    coach.availability = 'availability' in request.form
    coach.introduction = request.form.get('introduction')
    
    # 处理照片上传
    photo = request.files.get('photo')
    if photo and photo.filename and allowed_file(photo.filename):
        filename = secure_filename(f"coach_{int(time.time())}_{photo.filename}")
        photo.save(os.path.join(Config.UPLOAD_FOLDER, filename))
        coach.photo = filename
    
    db.session.commit()
    
    flash('教练信息更新成功', 'success')
    return redirect(url_for('admin_coaches'))

# 删除教练
@main_bp.route('/admin/coaches/<int:id>/delete')
@login_required
@admin_required
def admin_delete_coach(id):
    coach = Coach.query.get_or_404(id)
    
    # 检查是否有关联的预约
    bookings = Booking.query.filter_by(coach_id=id).all()
    if bookings:
        flash('无法删除该教练，因为存在关联的预约记录', 'danger')
        return redirect(url_for('admin_coaches'))
    
    db.session.delete(coach)
    db.session.commit()
    
    flash('教练删除成功', 'success')
    return redirect(url_for('admin_coaches'))

# 预约管理
@main_bp.route('/admin/bookings')
@login_required
@admin_required
def admin_bookings():
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    filter_type = request.args.get('filter', 'all')
    
    query = Booking.query
    
    # 搜索
    if search:
        query = query.join(User).join(Course).filter(
            or_(
                User.username.like(f'%{search}%'),
                Course.name.like(f'%{search}%')
            )
        )
    
    # 过滤
    if filter_type == 'pending':
        query = query.filter_by(status='pending')
    elif filter_type == 'confirmed':
        query = query.filter_by(status='confirmed')
    elif filter_type == 'completed':
        query = query.filter_by(status='completed')
    elif filter_type == 'cancelled':
        query = query.filter_by(status='cancelled')
    
    pagination = query.order_by(Booking.booking_date.desc()).paginate(page=page, per_page=10, error_out=False)
    bookings = pagination.items
    
    # 获取所有课程和教练，用于编辑预约
    courses = Course.query.all()
    coaches = Coach.query.filter_by(availability=True).all()
    
    return render_template('admin/bookings.html', bookings=bookings, pagination=pagination, courses=courses, coaches=coaches)

# 编辑预约
@main_bp.route('/admin/bookings/<int:id>/edit', methods=['POST'])
@login_required
@admin_required
def admin_edit_booking(id):
    booking = Booking.query.get_or_404(id)
    
    course_id = request.form.get('course_id', type=int)
    coach_id = request.form.get('coach_id', type=int)
    booking_date = request.form.get('booking_date')
    participants = request.form.get('participants', type=int)
    status = request.form.get('status')
    payment_status = request.form.get('payment_status')
    total_price = request.form.get('total_price', type=float)
    is_group = 'is_group' in request.form
    
    booking.course_id = course_id
    booking.coach_id = coach_id
    booking.booking_date = datetime.fromisoformat(booking_date)
    booking.participants = participants
    booking.status = status
    booking.payment_status = payment_status
    booking.total_price = total_price
    booking.is_group = is_group
    
    db.session.commit()
    
    flash('预约信息更新成功', 'success')
    return redirect(url_for('admin_bookings'))

# 删除预约
@main_bp.route('/admin/bookings/<int:id>/delete')
@login_required
@admin_required
def admin_delete_booking(id):
    booking = Booking.query.get_or_404(id)
    
    db.session.delete(booking)
    db.session.commit()
    
    flash('预约删除成功', 'success')
    return redirect(url_for('admin_bookings'))

# 活动管理
@main_bp.route('/admin/activities')
@login_required
@admin_required
def admin_activities():
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    filter_type = request.args.get('filter', 'all')
    
    query = Activity.query
    
    # 搜索
    if search:
        query = query.filter(Activity.title.like(f'%{search}%'))
    
    # 过滤
    if filter_type == 'upcoming':
        query = query.filter(Activity.date >= datetime.now())
    elif filter_type == 'past':
        query = query.filter(Activity.date < datetime.now())
    
    pagination = query.order_by(Activity.date.desc()).paginate(page=page, per_page=10, error_out=False)
    activities = pagination.items
    
    return render_template('admin/activities.html', activities=activities, pagination=pagination)

# 添加活动
@main_bp.route('/admin/activities/add', methods=['POST'])
@login_required
@admin_required
def admin_add_activity():
    title = request.form.get('title')
    description = request.form.get('description')
    date = request.form.get('date')
    
    # 处理图片上传
    image = request.files.get('image')
    if image and allowed_file(image.filename):
        filename = secure_filename(f"activity_{int(time.time())}_{image.filename}")
        image.save(os.path.join(Config.UPLOAD_FOLDER, filename))
    else:
        flash('请上传有效的图片文件', 'danger')
        return redirect(url_for('admin_activities'))
    
    activity = Activity(
        title=title,
        description=description,
        date=datetime.fromisoformat(date),
        image=filename,
        created_at=datetime.utcnow()
    )
    
    db.session.add(activity)
    db.session.commit()
    
    flash('活动添加成功', 'success')
    return redirect(url_for('admin_activities'))

# 编辑活动
@main_bp.route('/admin/activities/<int:id>/edit', methods=['POST'])
@login_required
@admin_required
def admin_edit_activity(id):
    activity = Activity.query.get_or_404(id)
    
    activity.title = request.form.get('title')
    activity.description = request.form.get('description')
    activity.date = datetime.fromisoformat(request.form.get('date'))
    
    # 处理图片上传
    image = request.files.get('image')
    if image and image.filename and allowed_file(image.filename):
        filename = secure_filename(f"activity_{int(time.time())}_{image.filename}")
        image.save(os.path.join(Config.UPLOAD_FOLDER, filename))
        activity.image = filename
    
    db.session.commit()
    
    flash('活动信息更新成功', 'success')
    return redirect(url_for('admin_activities'))

# 删除活动
@main_bp.route('/admin/activities/<int:id>/delete')
@login_required
@admin_required
def admin_delete_activity(id):
    activity = Activity.query.get_or_404(id)
    
    db.session.delete(activity)
    db.session.commit()
    
    flash('活动删除成功', 'success')
    return redirect(url_for('admin_activities'))

# 文件上传辅助函数
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif'}

@main_bp.route('/test')
def test():
    return "测试路由正常工作！"

@main_bp.route('/test-page')
def test_page():
    return render_template('test.html')

@main_bp.route('/booking-info')
def booking_info():
    """显示预约信息页面，不需要指定课程"""
    courses = Course.query.all()
    return render_template('booking_info.html', courses=courses) 
@main_bp.route('/post/<int:id>')
def post_detail(id):
    post = Post.query.get_or_404(id)
    return render_template('post_detail.html', post=post)

@main_bp.route('/admin/courses')
@login_required
@admin_required
def admin_courses():
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    filter_type = request.args.get('filter', 'all')
    
    query = Course.query
    
    # 搜索
    if search:
        query = query.filter(Course.name.like(f'%{search}%'))
    
    # 过滤
    if filter_type == 'experience':
        query = query.filter_by(type='体验潜水')
    elif filter_type == 'certified':
        query = query.filter_by(type='执证潜水')
    elif filter_type == 'certification':
        query = query.filter_by(type='考证课程')
    
    pagination = query.order_by(Course.id.desc()).paginate(page=page, per_page=10, error_out=False)
    courses = pagination.items
    
    return render_template('admin/courses.html', courses=courses, pagination=pagination)

@main_bp.route('/admin/posts')
@login_required
@admin_required
def admin_posts():
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '')
    filter_type = request.args.get('filter', 'all')
    
    query = Post.query
    
    # 搜索
    if search:
        query = query.filter(Post.title.like(f'%{search}%'))
    
    # 过滤
    if filter_type == 'knowledge':
        query = query.filter_by(category='潜水知识')
    elif filter_type == 'news':
        query = query.filter_by(category='新闻动态')
    elif filter_type == 'story':
        query = query.filter_by(category='潜水故事')
    
    pagination = query.order_by(Post.created_at.desc()).paginate(page=page, per_page=10, error_out=False)
    posts = pagination.items
    
    return render_template('admin/posts.html', posts=posts, pagination=pagination)

@main_bp.route('/admin/settings')
@login_required
@admin_required
def admin_settings():
    # 网站设置页面
    return render_template('admin/settings.html')

@main_bp.route('/admin/courses/<int:id>/edit', methods=['POST'])
@login_required
@admin_required
def admin_edit_course(id):
    course = Course.query.get_or_404(id)
    
    course.name = request.form.get('name')
    course.description = request.form.get('description')
    course.price = request.form.get('price', type=float)
    course.duration = request.form.get('duration')
    course.difficulty = request.form.get('difficulty')
    course.type = request.form.get('type')
    
    # 处理图片上传
    image = request.files.get('image')
    if image and image.filename and allowed_file(image.filename):
        filename = secure_filename(f"course_{int(time.time())}_{image.filename}")
        image.save(os.path.join(Config.UPLOAD_FOLDER, filename))
        course.image = filename
    
    db.session.commit()
    
    flash('课程信息更新成功', 'success')
    return redirect(url_for('main.admin_courses'))

@main_bp.route('/admin/courses/add', methods=['POST'])
@login_required
@admin_required
def admin_add_course():
    name = request.form.get('name')
    description = request.form.get('description')
    price = request.form.get('price', type=float)
    duration = request.form.get('duration')
    difficulty = request.form.get('difficulty')
    type = request.form.get('type')
    
    # 处理图片上传
    image = request.files.get('image')
    if image and allowed_file(image.filename):
        filename = secure_filename(f"course_{int(time.time())}_{image.filename}")
        image.save(os.path.join(Config.UPLOAD_FOLDER, filename))
    else:
        filename = 'default-course.jpg'
    
    course = Course(
        name=name,
        description=description,
        price=price,
        duration=duration,
        difficulty=difficulty,
        type=type,
        image=filename
    )
    
    db.session.add(course)
    db.session.commit()
    
    flash('课程添加成功', 'success')
    return redirect(url_for('main.admin_courses'))

@main_bp.route('/admin/courses/<int:id>/delete')
@login_required
@admin_required
def admin_delete_course(id):
    course = Course.query.get_or_404(id)
    
    # 检查是否有关联的预约
    bookings = Booking.query.filter_by(course_id=id).all()
    if bookings:
        flash('无法删除该课程，因为存在关联的预约记录', 'danger')
        return redirect(url_for('main.admin_courses'))
    
    db.session.delete(course)
    db.session.commit()
    
    flash('课程删除成功', 'success')
    return redirect(url_for('main.admin_courses'))

@main_bp.route('/admin/posts/add', methods=['POST'])
@login_required
@admin_required
def admin_add_post():
    title = request.form.get('title')
    content = request.form.get('content')
    category = request.form.get('category')
    
    # 处理图片上传
    image = request.files.get('image')
    if image and allowed_file(image.filename):
        filename = secure_filename(f"post_{int(time.time())}_{image.filename}")
        image.save(os.path.join(Config.UPLOAD_FOLDER, filename))
    else:
        filename = 'default-post.jpg'
    
    post = Post(
        title=title,
        content=content,
        category=category,
        image=filename,
        created_at=datetime.utcnow()
    )
    
    db.session.add(post)
    db.session.commit()
    
    flash('文章添加成功', 'success')
    return redirect(url_for('main.admin_posts'))

@main_bp.route('/admin/posts/<int:id>/edit', methods=['POST'])
@login_required
@admin_required
def admin_edit_post(id):
    post = Post.query.get_or_404(id)
    
    post.title = request.form.get('title')
    post.content = request.form.get('content')
    post.category = request.form.get('category')
    
    # 处理图片上传
    image = request.files.get('image')
    if image and image.filename and allowed_file(image.filename):
        filename = secure_filename(f"post_{int(time.time())}_{image.filename}")
        image.save(os.path.join(Config.UPLOAD_FOLDER, filename))
        post.image = filename
    
    db.session.commit()
    
    flash('文章更新成功', 'success')
    return redirect(url_for('main.admin_posts'))

@main_bp.route('/admin/posts/<int:id>/delete')
@login_required
@admin_required
def admin_delete_post(id):
    post = Post.query.get_or_404(id)
    
    db.session.delete(post)
    db.session.commit()
    
    flash('文章删除成功', 'success')
    return redirect(url_for('main.admin_posts'))

@main_bp.route('/admin/settings/update', methods=['POST'])
@login_required
@admin_required
def admin_update_settings():
    # 处理基本信息设置更新
    # 这里需要创建一个Settings模型来存储设置
    # 暂时使用简化版本
    flash('基本信息设置已更新', 'success')
    return redirect(url_for('main.admin_settings'))

@main_bp.route('/admin/settings/social', methods=['POST'])
@login_required
@admin_required
def admin_update_social():
    # 处理社交媒体设置更新
    flash('社交媒体设置已更新', 'success')
    return redirect(url_for('main.admin_settings'))

@main_bp.route('/admin/settings/seo', methods=['POST'])
@login_required
@admin_required
def admin_update_seo():
    # 处理SEO设置更新
    flash('SEO设置已更新', 'success')
    return redirect(url_for('main.admin_settings'))

@main_bp.route('/admin/settings/system', methods=['POST'])
@login_required
@admin_required
def admin_update_system():
    # 处理系统设置更新
    flash('系统设置已更新', 'success')
    return redirect(url_for('main.admin_settings'))
